<template>
  <div class="article-detail">
    <div v-if="loading" class="loading">加载中...</div>
    
    <template v-else-if="article">
      <h1>{{ article.title }}</h1>
      <div class="meta">
        <span>作者：{{ article.author }}</span>
        <span>发布日期：{{ formatDate(article.date) }}</span>
      </div>
      
      <img v-if="article.image" :src="article.image" :alt="article.title" class="cover-image">
      
      <div class="content" v-html="article.content"></div>
      
      <div class="actions">
        <RouterLink to="/" class="back-link">返回列表</RouterLink>
      </div>
    </template>
    
    <div v-else class="not-found">
      <h2>文章不存在</h2>
      <RouterLink to="/">返回首页</RouterLink>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, watch } from 'vue'
import { useRoute } from 'vue-router'
import { fetchArticle } from '@/api/articles'

const route = useRoute()
const loading = ref(true)
const article = ref(null)

const loadArticle = async () => {
  try {
    loading.value = true
    article.value = await fetchArticle(route.params.id)
  } catch (error) {
    console.error('加载文章失败:', error)
    article.value = null
  } finally {
    loading.value = false
  }
}

const formatDate = (dateString) => {
  return new Date(dateString).toLocaleDateString()
}

onMounted(loadArticle)

watch(() => route.params.id, loadArticle)
</script>

<style scoped>
.article-detail {
  max-width: 800px;
  margin: 0 auto;
  padding: 2rem;
}

.loading {
  text-align: center;
  padding: 2rem;
}

.meta {
  color: #666;
  margin: 1rem 0;
  display: flex;
  gap: 1.5rem;
}

.cover-image {
  width: 100%;
  max-height: 400px;
  object-fit: cover;
  margin: 1rem 0;
}

.content {
  line-height: 1.8;
  margin: 2rem 0;
}

.not-found {
  text-align: center;
  padding: 2rem;
}

.back-link {
  display: inline-block;
  margin-top: 2rem;
  color: #2c3e50;
  text-decoration: none;
  border: 1px solid #2c3e50;
  padding: 0.5rem 1rem;
  border-radius: 4px;
}

.back-link:hover {
  background-color: #f0f0f0;
}
</style>